//
//  SelePayViewController.swift
//  ZNZXSuperMarket
//
//  Created by 四川中农 on 2018/8/23.
//  Copyright © 2018年 四川中农. All rights reserved.
//

import UIKit
import HandyJSON

class SelePayViewController: BaseViewController {
    
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var balancePayLabel: UILabel!
    
    var model:ConfirmOrderModel!
    
    var type = 0
    
    lazy var alertView : AlertContentView = {
        let view = AlertContentView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: UIScreen.ScreenHeight),type:0)
        view.backPassWordValue = { [weak self] (value) in
            self?.balancePay(value: value)
        }
        UIApplication.shared.keyWindow?.addSubview(view)
        return view
    }()
    
    lazy var rechargeAlertView : AlertContentView = {
        let view = AlertContentView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.ScreenWidth, height: UIScreen.ScreenHeight))
        UIApplication.shared.keyWindow?.addSubview(view)
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.title = "支付"
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(labelTap))
        self.balancePayLabel.isUserInteractionEnabled = true
        self.balancePayLabel.addGestureRecognizer(tap)
        
        self.tableView.backgroundColor = UIColor.backgroundColor
        self.tableView.delegate = self
        self.tableView.dataSource = self
        
        let attributedString = NSMutableAttributedString(string: "余额支付")
        attributedString.addAttributes([
            NSAttributedStringKey.underlineStyle:1,
            NSAttributedStringKey.foregroundColor:UIColor.init(hexColor: "#333333")], range: NSRange(location: 0, length: 4))
        self.balancePayLabel.attributedText = attributedString
        
        
        
    }
    
    override func backBarButtonMethon() {
        self.navigationController?.popToRootViewController(animated: true)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        NotificationCenter.default.addObserver(self, selector: #selector(receivePayResult(notification:)), name: NSNotification.Name(rawValue: "payResult"), object: nil)
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "payResult"), object: nil)
    }
    
    @objc func receivePayResult(notification:Notification){
        
        guard let userInfo = notification.object else {
            return
        }
        if (userInfo as! postParameters)["isSuccess"] as! Bool == true {
            PKhud.showText(text: "支付成功啦~")
            Utils.DispatchAfter(after: 2) {
                let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "CheckstandViewController") as!  CheckstandViewController
                ctrl.payType = self.type == 0 ? OrderPayType.alipay : OrderPayType.wechat
                ctrl.isBalancePay = false
                self.navigationController?.pushViewController(ctrl, animated: true)
            }
        }else{
            self.rechargeAlertView.showRechargeAlert(title: "订单支付失败", content: (self.type == 0 ? "支付宝" : "微信") + "支付失败，本次订单未完成")
        }
    }
    
    
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "payResult"), object: nil)
    }
    
    // MARK:余额支付
    @objc func labelTap(){
        self.alertView.showAlert()
    }
    
    func balancePay(value:String){
        
        let password = Utils.getUserDefaulsFor(key: "password") as! String
        guard value.MD5String == password else{
            PKhud.showText(text: "密码不正确~")
            return
        }
        var orderIDs = ""
        for orderModel in self.model.orders! {
            orderIDs = orderIDs + "\(orderModel.id)" + ","
        }
        
        let endIndex = orderIDs.index(orderIDs.startIndex, offsetBy: orderIDs.count - 1)
        let str = String(orderIDs[..<endIndex])
        
        PKhud.show()
        HttpRequest.requestData(.get, URLString: Api.payBalance.rawValue, parameters: ["orderId":str]) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                
                if let model = JSONDeserializer<PayBalanceModel>.deserializeFrom(dict: result["data"] as? postParameters) {
                    if model.type == 0 {
                        // type == 0 成功
                        let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "CheckstandViewController") as!  CheckstandViewController
                        ctrl.model = model
                        self.navigationController?.pushViewController(ctrl, animated: true)
                    }else{
                        // type == 1 失败
                        let ctrl = Utils.instantiateInitialViewControllerWith(storyBoardName: "Main", identitier: "BalanceCheckstandTableViewController") as! BalanceCheckstandTableViewController
                        ctrl.model = model
                        self.navigationController?.pushViewController(ctrl, animated: true)
                    }
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

extension SelePayViewController:UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return (self.model.orders?.count)! + 2
        }else{
            return 2
        }
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            if indexPath.row <= self.model.orders!.count {
                let cell = tableView.dequeueReusableCell(withIdentifier: "SelePayOrderTableViewCell") as! SelePayOrderTableViewCell
                if indexPath.row < self.model.orders!.count {
                    cell.updateViews(title: "订单号", rightString: self.model.orders![indexPath.row].number, isPrice: false)
                }else{
                    cell.updateViews(title: "待付款", rightString: self.model.money, isPrice: true)
                }
                return cell
            }else{
                let cell = tableView.dequeueReusableCell(withIdentifier: "SelePayReminderTableViewCell") as! SelePayReminderTableViewCell
                cell.reload(withModel: self.model)
                return cell
            }
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "PayTypeTableViewCell") as! PayTypeTableViewCell
            if indexPath.row == 0 {
                cell.updateViews(withImage: "zhifu_zfb", title: "支付宝", detail: "可能超出发卡行单次支付最大额度")
            }else{
                cell.updateViews(withImage: "zhifu_wx", title: "微信", detail: "推荐安装微信5.0及以上版本用户使用")
            }
            return cell
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 && indexPath.row == self.model.orders!.count + 1{
            return 50
        }else{
            return 55
        }
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1 {
            return 10
        }
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard indexPath.section == 1 else {
            return
        }
        
        (UIApplication.shared.delegate as! AppDelegate).type = .order
        
        var orderIDs = ""
        for orderModel in self.model.orders! {
            orderIDs = orderIDs + "\(orderModel.id)" + ","
        }
        
        let endIndex = orderIDs.index(orderIDs.startIndex, offsetBy: orderIDs.count - 1)
        let str = String(orderIDs[..<endIndex])
        
        if indexPath.section == 1 && indexPath.row == 1 {
            // 微信支付
            self.type = 1
        }
        
        PKhud.show()
        HttpRequest.requestData(.post, URLString: Api.payGet.rawValue, parameters: ["orderId":str,"type":self.type]) { (result) in
            PKhud.hiden()
            if result["msg"] as! String == "success"{
                if self.type == 0 {
                    // 支付宝
                    AlipaySDK.defaultService().payOrder(result["data"] as! String, fromScheme: "zxsupermarket", callback: { (resultDic) in
                        
                    })
                }else{
                    
                    let isInstall = WXApi.isWXAppInstalled()
                    guard isInstall else {
                        PKhud.showText(text: "您尚未安装微信客户端~")
                        return
                    }
                     // 微信
                    if let dic = result["data"] as? postParameters {
                        let request = PayReq.init()
                        request.partnerId = dic["partnerid"] as! String
                        request.prepayId = dic["prepayid"] as! String
                        request.package = dic["package"] as! String
                        request.nonceStr = dic["noncestr"] as! String
                        request.timeStamp = UInt32(dic["timestamp"] as! String)!
                        request.sign = dic["sign"] as! String
                        WXApi.send(request)
                    }
                }
            }else{
                PKhud.showText(text: result["data"] as! String)
            }
        }
    }
}



































